package com.bilibili.dubbo.api;

import com.bilibili.dubbo.api.mongo.BaiduApi;
import com.bilibili.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;


/**
 * @author HuangRongFu
 * 2021/11/25 星期四8:02 下午
 */

@DubboService
public class BaiduApiImpl implements BaiduApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存地理位置
     *
     * @param userId
     * @param latitude
     * @param longitude
     * @param address
     * @Return: null
     */
    @Override
    public void save(Long userId, Double latitude, Double longitude, String address) {

        long timeMillis = System.currentTimeMillis();

        Query query = new Query(Criteria.where("userId").is(userId));

        GeoJsonPoint geoJsonPoint = new GeoJsonPoint(latitude, longitude);

        if (mongoTemplate.exists(query, UserLocation.class)){

            Update update = new Update();
            update.set("location", geoJsonPoint);
            update.set("address", address);
            update.set("updated", timeMillis);

            mongoTemplate.updateFirst(query, update, UserLocation.class);
        }else {

            //3. 不存在则添加记录
            UserLocation userLocation = new UserLocation();
            userLocation.setUserId(userId);
            userLocation.setUpdated(timeMillis);
            userLocation.setCreated(timeMillis);
            userLocation.setLocation(geoJsonPoint);
            userLocation.setAddress(address);
            mongoTemplate.insert(userLocation);

        }
    }
}
